<template>
  <div>
    <el-card v-loading="loading">

      <avue-crud :data="data" :option="option" @refresh-change="refreshChange" @row-save="rowSave" @row-update="rowUpdate"
        @row-del="rowDel"></avue-crud>
    </el-card>

  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addUser, manageuser, userdelinfo, manageuserupdate } from '@/api/user.ts'
import { useUserStore } from '@/store/modules/user'

const { userMessage } = useUserStore()

const loading = ref(true)
const data = ref([]);

const getData = () => {
  loading.value = true
  manageuser().then(res => {
    if (userMessage.qx == 0) {
      data.value = res.result
    } else {
      data.value = res.result.filter(v => v.id == userMessage.id)
    }

    loading.value = false
  })
}


getData()

const option = ref({
  addBtn: userMessage.qx == 0,
  delBtn: userMessage.qx == 0,
  column: [
    { label: '用户名', prop: 'username', rules: [{ required: true, message: '请输入用户名', trigger: 'blur' }], editDisabled: !userMessage.qx == 0, },
    { label: '密码', prop: 'password', rules: [{ required: true, message: '请输入密码', trigger: 'blur' }] },
    { label: '人员姓名', prop: 'name', rules: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }] },
    {
      label: '权限', prop: 'qx', type: 'select', dicData: [{
        label: '超级管理员',
        value: 0
      }, {
        label: '普通用户',
        value: 1
      }],
      rules: [{ required: true, message: '请选择权限', trigger: 'blur' }],
      editDisabled: !userMessage.qx == 0,
    },

  ]
});



const refreshChange = () => {
  getData()
};

const rowSave = (form, done, loading) => {
  // loading();
  addUser(form).then(res => {
    if (res !== 'error') {
      done(form);
    } else {
      done();
    }
  })

};

const rowDel = (form, index, done) => {
  ElMessageBox.confirm('是否删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userdelinfo(form.id).then(res => {
      ElMessage.success('删除成功!');
      done(form);

    })

  }).catch(() => { });
};

const rowUpdate = (form, index, done, loading) => {

  manageuserupdate(form).then(res => {
    ElMessage.success('修改成功');
    done(form);
    if (form.id == userMessage.id) {
      Object.keys(userMessage).forEach(key => {
        userMessage[key] = form[key]
      });
    }
  })
};
</script>